package fr.sedoo.commons.client.widget.table;

import java.util.List;
import java.util.ListIterator;
import java.util.Set;

import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ListDataProvider;

import fr.sedoo.commons.shared.domain.HasIdentifier;

public abstract class AbstractListTable extends AbstractTable {

	protected List<? extends HasIdentifier> model;

	private final ListDataProvider<HasIdentifier> dataProvider;

	public AbstractListTable() {
		super();
		dataProvider = getDataProvider();

	}

	@Override
	protected ListDataProvider<HasIdentifier> getDataProvider() {
		return new ListDataProvider<HasIdentifier>();
	}

	public List<? extends HasIdentifier> getModel() {
		return model;
	}

	public void setModel(List<? extends HasIdentifier> model) {
		this.model = model;
	}

	public void init(List<? extends HasIdentifier> model) {
		setModel(model);
		checkEmptyPanelVisibility();
		// TODO : Tester si on la pas déjà fait
		Set<HasData<HasIdentifier>> dataDisplays = dataProvider.getDataDisplays();
		if (dataDisplays.size() != 0) {
			dataProvider.removeDataDisplay(itemTable);
		}
		dataProvider.addDataDisplay(itemTable);
		/*
		 * List<HasId> list = dataProvider.getList(); list.clear();
		 * list.addAll(this.model);
		 */

		itemTable.setRowData(model);
	}

	public void removeRow(String id) {

		ListIterator<? extends HasIdentifier> listIterator = model.listIterator();
		while (listIterator.hasNext()) {
			HasIdentifier hasId = listIterator.next();
			if (hasId.getIdentifier().compareTo(id) == 0) {
				listIterator.remove();
				break;
			}
		}
		init(model);
	}

	@Override
	public boolean isEmpty() {
		return (this.model == null) || (this.model.size() == 0);
	}

	public HasIdentifier getItemById(String id) {
		ListIterator<? extends HasIdentifier> listIterator = model.listIterator();
		while (listIterator.hasNext()) {
			HasIdentifier hasId = listIterator.next();
			if (hasId.getIdentifier().compareTo(id) == 0) {
				return hasId;
			}
		}
		return null;
	}

	

}
